package com.campus.controller;

import com.campus.domain.dto.AddUserDTO;
import com.campus.domain.dto.UpdateUserDTO;
import com.campus.domain.dto.UserDTO;
import com.campus.domain.dto.UserQueryDTO;
import com.campus.domain.vo.PageResultVO;
import com.campus.domain.vo.Result;
import com.campus.domain.vo.UserVO;
import com.campus.service.IAdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/user")
@Slf4j
public class AdminUserController {

    @Autowired
    private IAdminUserService adminUserService;

    /**
     * 获取用户列表（分页）
     */
    @GetMapping("/list")
    public Result<PageResultVO<UserVO>> getUserList(UserQueryDTO queryDTO) {
        log.info("获取用户列表，查询参数：{}", queryDTO);
        PageResultVO<UserVO> result = adminUserService.getUserList(queryDTO);
        return Result.ok(result);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    public Result<String> addUser(@RequestBody AddUserDTO dto) {
        log.info("添加用户：{}", dto);
        adminUserService.addUser(dto);
        return Result.ok("添加成功");
    }

    /**
     * 更新用户
     */
    @PutMapping("/update/{id}")
    public Result<String> updateUser(@PathVariable("id") Long id, @RequestBody UpdateUserDTO dto) {
        log.info("更新用户，ID：{}，数据：{}", id, dto);
        adminUserService.updateUser(id, dto);
        return Result.ok("更新成功");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteUser(@PathVariable("id") Long id) {
        log.info("删除用户，ID：{}", id);
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        
        // 不能删除自己
        if (userDTO.getId().equals(id)) {
            return Result.fail("不能删除当前登录用户");
        }
        
        adminUserService.deleteUser(id);
        return Result.ok("删除成功");
    }
}
